package com.example.palyerdemo

/**
 * 负责段落切分、删除标记与逻辑/真实时间映射。
 *
 * 概念：
 * - 真实时间：媒体文件的自然时间线。
 * - 逻辑时间：过滤掉被删除区间后的压缩时间线，用于 UI 显示和用户拖拽。
 *
 * 设计要点：
 * - 不修改媒体源，所有“删除”都通过跳过/映射实现。
 * - [remainingDurationMs] = 所有未删除段的时长总和。
 */
class SegmentManager(
    totalDurationMs: Long,
    segmentCount: Int
) {
    val segments: MutableList<Segment>

    init {
        require(totalDurationMs > 0)
        require(segmentCount > 0)
        val segmentDuration = totalDurationMs / segmentCount
        val acc = mutableListOf<Segment>()
        var start = 0L
        for (i in 0 until segmentCount) {
            val end = if (i == segmentCount - 1) totalDurationMs else start + segmentDuration
            acc += Segment(index = i, startMs = start, endMs = end)
            start = end
        }
        segments = acc
    }

    /** 标记/取消某段的删除状态。 */
    fun setDeleted(index: Int, deleted: Boolean) {
        val seg = segments.getOrNull(index) ?: return
        seg.deleted = deleted
    }

    /** 切换某段的删除状态。 */
    fun toggle(index: Int) {
        val seg = segments.getOrNull(index) ?: return
        seg.deleted = !seg.deleted
    }

    /** 当前逻辑时间线的总时长（去除删除段）。*/
    fun remainingDurationMs(): Long {
        return segments.filter { !it.deleted }.sumOf { it.durationMs }
    }

    /** 所有未删除的段落列表（实时视图）。*/
    fun keptSegments(): List<Segment> = segments.filter { !it.deleted }

    /** 根据真实时间查找所属段。*/
    fun findSegmentByPosition(realPositionMs: Long): Segment? {
        return segments.firstOrNull { realPositionMs in it.startMs until it.endMs }
    }

    /**
     * 查找从 realPositionMs 开始的下一个可播放段的起点；
     * - 若 already in kept segment，则返回当前位置；
     * - 若不存在后续 kept 段，则返回 null。
     */
    fun nextKeptStartAfter(realPositionMs: Long): Long? {
        // 如果当前位置在可播放段内，返回当前位置；否则返回下一个可播放段起点
        val current = findSegmentByPosition(realPositionMs)
        if (current != null && !current.deleted) return realPositionMs
        val next = segments.firstOrNull { !it.deleted && it.startMs >= realPositionMs }
        return next?.startMs
    }

    /** 逻辑时间 -> 真实时间。*/
    fun logicalToReal(logicalPositionMs: Long): Long {
        var remaining = logicalPositionMs
        keptSegments().forEach { seg ->
            val segDur = seg.durationMs
            if (remaining < segDur) {
                return seg.startMs + remaining
            }
            remaining -= segDur
        }
        // 越界则返回最后一个可播放段末尾
        val last = keptSegments().lastOrNull() ?: return 0L
        return last.endMs
    }

    /** 真实时间 -> 逻辑时间。*/
    fun realToLogical(realPositionMs: Long): Long {
        var logical = 0L
        keptSegments().forEach { seg ->
            if (realPositionMs >= seg.endMs) {
                logical += seg.durationMs
            } else if (realPositionMs >= seg.startMs) {
                logical += (realPositionMs - seg.startMs)
                return logical
            } else {
                return logical
            }
        }
        return logical
    }
}


